#!/bin/bash

function close_firewall() {
  systemctl stop firewalld.service
  systemctl disable firewalld.service
}

function install_docker() {
  if ! type docker &>/dev/null ; then
      # 安装需要的软件包
      sudo yum install -y yum-utils device-mapper-persistent-data lvm2
      # 设置yum源
      sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
      # 安装docker
      sudo yum install -y docker-ce
      # 启动docker
      sudo systemctl start docker
      sudo systemctl enable docker
  fi
  return
}

function install_pip() {
  if ! type pip &>/dev/null ; then
      yum -y install epel-release
      sleep 5
      yum -y install python-pip
  fi
  return
}

function install_docker_compose() {
  if ! type docker-compose &>/dev/null ; then
      yum install -y gcc
      sleep 3
      yum install -y python-devel
      sleep 3
      pip install --upgrade setuptools==41.0.0 -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host=pypi.tuna.tsinghua.edu.cn
      pip install --upgrade pip==19.2.3 -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host=pypi.tuna.tsinghua.edu.cn
      pip install -r env_requirement.txt -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host=pypi.tuna.tsinghua.edu.cn
      pip install docker-compose -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host=pypi.tuna.tsinghua.edu.cn
  fi
  return
}

function run() {
    project_status=$(netstat -lntp | grep 0.0.0.0:80)
    if [ "x${project_status}" != "x" ]; then
        echo "项目已经启动"
        exit 1
    fi
    if [ ! -f "docker-compose.yml" ]; then
        echo "无法正常启动项目"
        exit 1
    fi
    docker-compose up -d
}


function main() {
  firewall_status=$(firewall-cmd --state)
  if [ "${firewall_status}" == "running" ]; then
     close_firewall ||exit 1
  fi
  install_pip || exit 1
  install_docker || exit 1
  install_docker_compose || exit 1
  run || exit 1
  echo "project start success!!!"
}

# shellcheck disable=SC2068
main $@
